package mesweb.mesweb.Utils;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import com.baomidou.mybatisplus.core.toolkit.support.ColumnCache;
import org.springframework.cglib.core.ReflectUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @Description: TODO
 * @Author niufw
 * @Date 2022/1/3 15:36
 * @Version 1.0
 */

public class QueryWrapperUtil<T> {

    public QueryWrapper<T> build(Class clazz, T t) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        if (null == clazz) return queryWrapper;
        Map<String, ColumnCache> columnCacheMap = LambdaUtils.getColumnMap(clazz);
        if (null != columnCacheMap) {
            PropertyDescriptor[] propertyDescriptors = ReflectUtils.getBeanProperties(clazz);
            for (Map.Entry<String, ColumnCache> entry : columnCacheMap.entrySet()
            ) {
                for (PropertyDescriptor prop : propertyDescriptors
                ) {
                    if (prop.getName().toUpperCase().equals(entry.getKey())) {
                        Method rm = prop.getReadMethod();
                        Object obj = null;
                        try {
                            obj = rm.invoke(t);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                        if (null != obj) {
                            queryWrapper.eq(entry.getValue().getColumn(), Convert.convert(prop.getPropertyType(), obj));
                            break;
                        }
                    }
                }
            }
        }
        return queryWrapper;
    }
}
